package it.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;

import it.pojo.Student;
import it.service.IStudentService;
import it.util.IPUtil;

@Controller
@RequestMapping("/student")
public class StudentController {

	@Autowired
	private IStudentService studentService;

	@RequestMapping("/regist")
	public String regist(Student student, HttpServletRequest request) {
		// 检验验证码
		String valcode = (String) request.getSession().getAttribute("valcode");
		String vode = request.getParameter("vcode");
		if (null == vode || !valcode.equals(vode)) {
			request.setAttribute("student", student);
			request.setAttribute("vcode", "验证码不正确");
			return "forward:/";
		}
		// 获取ip
		String IP = IPUtil.getRemoteHost(request);
		student.setIp(IP);
		Map<String, String> userMap = this.studentService.createUser(student);
		if (null != userMap && !userMap.isEmpty()) {
			request.setAttribute("student", student);
			request.setAttribute("map", userMap);
			return "forward:/";
		}
		List<Student> students = this.studentService.getStudentList();
		request.setAttribute("students", students);
		return "success";

	}

	@RequestMapping("/success")
	public String success(Student student, HttpServletRequest request) {
		// 获取ip
		List<Student> students = this.studentService.getStudentList();
		request.setAttribute("students", students);
		return "success";

	}

	@InitBinder
	public void initBinder(ServletRequestDataBinder binder) {
		/**
		 * 自动转换日期类型的字段格式
		 */
		binder.registerCustomEditor(Date.class,
				new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"), true));

		/**
		 * 防止XSS攻击
		 */
		binder.registerCustomEditor(String.class, new StringEscapeEditor(true, false));

	}
}
